
import {Message} from 'element-ui';
import $ from "jquery";
class MUtil{
    request(param){
        var p = new Promise((resolve, reject) => {
            $.ajax({
                type        : param.type        || 'get',
                url         : param.url         || '',
                dataType    : param.dataType    || 'json',
                data        : param.data        || null,
                contentType: false,
                processData: false,
                headers :{
                    // 'token':this.getStorage("token")?this.getStorage('token'):'',
                    "Authorization":this.getStorage('token')?this.getStorage('token'):'',
                    // "Content-Type":'multipart/form-data'

                },
                success     : res => {
                    // 数据请求成功
                    if('0' === res.code){
                        typeof resolve === 'function' && resolve(res, res.message);
                    }else{
                        typeof reject === 'function' && reject(res.message || res);
                    }
                },
                error       : err => {
                    typeof reject === 'function' && reject(err.message);
                }
            });
        });
       return p;
    }
    // 获取URL参数
    getUrlParam(name){
        // param=123&param1=456
        let url=window.location.href.split('#')[1] || '',
            queryString = url.split('?')[1] || '',
            reg         = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
            result      = queryString.match(reg);
        return result ? decodeURIComponent(result[2]) : null;
    }
    // 本地存储
    setStorage(name, data){
        let dataType = typeof data;
        // json对象
        if(dataType === 'object'){
            window.localStorage.setItem(name, JSON.stringify(data));
        }
        // 基础类型
        else if(['number','string','boolean'].indexOf(dataType) >= 0){
            window.localStorage.setItem(name, data);
        }
        // 其他不支持的类型
        else{
            alert('该类型不能用于本地存储');
        }
    }
    // 取出本地存储内容
    getStorage(name){
        let data = window.localStorage.getItem(name);
        let dataType = typeof data;
        if(dataType === 'object'){
            return JSON.parse(data);
        }else if(['number','string','boolean'].indexOf(dataType) >= 0){
        	return data;
        }else{
            return '';
        }
    }
    // 删除本地存储
    removeStorage(name){
        window.localStorage.removeItem(name);
    }
    // 会话存储
    setSessionStorage(name, data){
        let dataType = typeof data;
        // json对象
        if(dataType === 'object'){
            window.sessionStorage.setItem(name, JSON.stringify(data));
        }
        // 基础类型
        else if(['number','string','boolean'].indexOf(dataType) >= 0){
            window.sessionStorage.setItem(name, data);
        }
        // 其他不支持的类型
        else{
            alert('该类型不能用于本地存储');
        }
    }
    // 取出会话存储内容
    getSessionStorage(name){
        let data = window.sessionStorage.getItem(name);
        let dataType = typeof data;
        if(dataType === 'object'){
            return JSON.parse(data);
        }else if(['number','string','boolean'].indexOf(dataType) >= 0){
        	return data;
        }else{
            return '';
        }
    }
    // 删除会话存储
    removeSessionStorage(name){
        window.sessionStorage.removeItem(name);
    }
    
    // 成功提示
    successTips(successMsg){
        Message({
            message: successMsg,
            type: 'success',
            duration: 5 * 1000
          })
    }
    // 错误提示
    errorTips(errMsg){
        Message({
            message: errMsg?errMsg:'网络开小差啦，获取信息失败',
            type: 'error',
            duration: 5 * 1000
        })
    }
    //时间格式转换
    formatDate (date, fmt) {
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        let o = {
            'M+': date.getMonth() + 1,
            'd+': date.getDate(),
            'h+': date.getHours(),
            'm+': date.getMinutes(),
            's+': date.getSeconds()
        };
        for (let k in o) {
            if (new RegExp(`(${k})`).test(fmt)) {
                let str = o[k] + '';
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : this.padLeftZero(str));
            }
        }
        return fmt;
    };
    padLeftZero (str) {
        return ('00' + str).substr(str.length);
    };
    //数组去重
    unique(arr) {
        if (!Array.isArray(arr)) {
            console.log('type error!')
            return;
        }
        arr = arr.sort();
        var result=[];
        var obj={}
        for (var i = 1; i < arr.length; i++) {
            if (!obj[arr[i].value]) {
                result.push(arr[i]);
                obj[arr[i].value] = true;
            }
        }
        return result;
    };
    //格式化时间
    formatTime(param) {
        let y = param.getFullYear();
        let m = param.getMonth() + 1;
        let d = param.getDate();
        m = m < 10 ? ("0" + m) : m;
        d = d < 10 ? ("0" + d) : d;
        return y + "-" + m + "-" + d + " ";
    };
    getDate(code) {
        const date = new Date();
        let endTime = this.formatTime(date);
        let date1 = Date.parse(date);
        let start = '';
        let end = '';
        let oneDay = 1000 * 3600 * 24;
      
        switch (code) {
          //今天
          case 'today':
            start = new Date();
            break;
          //最近2天
          case 'lastTwoDay':
            start = date1 - oneDay * 2;
            break;
          //最近1周
          case 'lastOneWeek':
            start = date1 - oneDay * 7;
            break;
          //最近2周
          case 'lastTwoWeek':
            start = date1 - oneDay * 14;
            break;
          //最近1月
          case 'lastOneMonth':
            start = new Date();
            start.setMonth(start.getMonth() - 1)
            break;
          //最近2月
          case 'lastTwoMonth':
            start = new Date();
            start.setMonth(start.getMonth() - 2)
            break;
          //最近3月
          case 'lastThreeMonth':
            start = new Date();
            start.setMonth(start.getMonth() - 3)
            break;
          //最近半年
          case 'lastHalfYear':
            start = date1 - oneDay * 183;
            break;
          //最近一年
          case 'lastOneYear':
            start = new Date();
            start.setYear(start.getFullYear() - 1)
            break;
          //本周
          case 'thisWeek':
            let a = 6 - date.getDay();
            start = new Date(date1 - oneDay * a).setHours(0, 0, 0, 0);
            end = new Date(date1 + oneDay * (1 + date.getDay())).setHours(24, 0, 0, 0)
            break;
          //本月
          case 'thisMonth':
            start = new Date();
            start.setHours(0, 0, 0, 0)
            start.setMonth(start.getMonth(), 1)
            end = new Date(start)
            end.setHours(0, 0, 0, 0)
            end.setMonth(start.getMonth() + 1, 1)
            break;
          //本年
          case 'thisYear':
            start = new Date();
            start.setHours(0, 0, 0, 0)
            start.setMonth(0, 1)
            start.setYear(start.getFullYear())
            end = new Date(start)
            end.setHours(0, 0, 0, 0)
            end.setMonth(start.getMonth(), 1)
            end.setYear(start.getFullYear() + 1)
            break;
        }
      
        return {
          startTime: this.formatTime(new Date(start)),
          endTime: end ? this.formatTime(new Date(end)) : endTime,
        }
    }
}
export default MUtil;